package org.example.controller;

import org.example.core.IWorkFlowService;
import org.example.model.WfDef;
import org.example.model.WfTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/wf")
public class WorkflowController {

    @Autowired
    private IWorkFlowService workFlowService;

    @RequestMapping("/test")
    public String test() {
        return "ok";
    }

    @GetMapping("/create")
    public String createAndDeployDynamicBpmn() {
        try {
            WfDef wfDef = new WfDef();
            wfDef.setId("wf01");
            wfDef.setName("流程01");
            buildTasks(wfDef);
            String deployId = workFlowService.createWorkflowAndDeploy(wfDef);
            return "BPMN file created, saved, and deployed successfully! deployId=" + deployId;
        } catch (Exception e) {
            return "Error while creating and saving BPMN file: " + e.getMessage();
        }
    }

    @GetMapping("/start")
    public void start() {
        String flowDefId = "wf01";
        String flowNo = UUID.randomUUID().toString();
        Map<String, Object> param = new HashMap<>();
        param.put("userId", 1);
        workFlowService.startFlow(flowDefId, flowNo, param);
    }

    @GetMapping("/commit")
    public void commit(String taskId) {
        Map<String,Object> variables = new HashMap<>();
        Map<String, Object> transientVariables = new HashMap<>();
        transientVariables.put("userId", 2);
        workFlowService.complete(taskId, variables, transientVariables);
    }

    @GetMapping("/approve")
    public void approve(String taskId, Boolean pass) {
        Map<String,Object> variables = new HashMap<>();
        Map<String, Object> transientVariables = new HashMap<>();
        transientVariables.put("userId", 3);
        transientVariables.put("pass", pass);
        workFlowService.complete(taskId, variables, transientVariables);
    }

    @GetMapping

    private static void buildTasks(WfDef wfDef) {
        List<WfTask> tasks = new ArrayList<>();
        wfDef.setWfTasks(tasks);

        WfTask wfTask = new WfTask();
        wfTask.setId("commit");
        wfTask.setName("提交审批");
        wfTask.setAssignee("${userId}");
        tasks.add(wfTask);

        wfTask = new WfTask();
        wfTask.setId("STL_AUDIT");
        wfTask.setName("小组长审批");
        wfTask.setAssignee("${userId}");
        tasks.add(wfTask);

        wfTask = new WfTask();
        wfTask.setId("TL_AUDIT");
        wfTask.setName("组长审批");
        wfTask.setAssignee("${userId}");
        tasks.add(wfTask);
    }
}
